# -*- coding: utf-8 -*-
# Tomado de https://bitbucket.org/mikl/satchmo (código abierto, ver http://goo.gl/RlKrG)
import re
import random
import unicodedata
from django.contrib.auth.models import User


_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

def random_string(length, variable=False, charset=_LETTERS):
    if variable:
        length = random.randrange(1, length+1)
    return ''.join([random.choice(charset) for x in xrange(length)])

_is_alnum_re = re.compile(r'\w+')
_ID_MIN_LENGTH = 5  # largo minimo de nombre de usuario
_ID_MAX_LENGTH = 30 # máximo largo de nombre de usuario (django.contrib.auth.models.User)

def _id_generator(first_name, last_name, email, dni):
    def _alnum(s, glue=''):
        return glue.join(filter(len, _is_alnum_re.findall(s))).lower()
    # Se genera el nombre de usuario intentando estos datos
    #  1. Apellido
    #  2. Apellido y nombre
    #  3. Parte de usuario del email
    #  4. DNI
    id = _alnum(unicodedata.normalize('NFKD', last_name).encode('ascii', 'ignore'))
    if len(id) >= _ID_MIN_LENGTH:
        yield id[:_ID_MAX_LENGTH]
    id = _alnum(unicodedata.normalize('NFKD', last_name + first_name ).encode('ascii', 'ignore'))
    if len(id) >= _ID_MIN_LENGTH:
        yield id[:_ID_MAX_LENGTH]
    id = _alnum(email.split('@')[0])
    if len(id) >= _ID_MIN_LENGTH:
        yield id[:_ID_MAX_LENGTH]
    id = _alnum(dni)
    if len(id) >= _ID_MIN_LENGTH:
        yield id[:_ID_MAX_LENGTH]
    while True:
        yield _alnum('%s_%s' % (id[:_ID_MIN_LENGTH], random_string(_ID_MIN_LENGTH, True)))[:_ID_MAX_LENGTH]

def generate_id(first_name='', last_name='', email='', dni=''):
    valid_id = False
    gen = _id_generator(first_name, last_name, email, dni)
    test_name = gen.next()
    while valid_id is False:
        try:
            User.objects.get(username=test_name)
        except User.DoesNotExist:
            valid_id = True
        else:
            test_name = gen.next()
    return test_name
